﻿
var Core = {

    ModalActividad: null
    , IdGridView: "#tblGridView"
    , ManttoPath: "/Paginas/Mantto/Default.aspx"
    , ProcessMessage: "Procesando ..."
    , ProcessImage: "/Assets/images/activity.gif"

    , IsInit: false
    , IsView: function() {
        return (Core.GetUrlParam("View") != "" && Core.GetUrlParam("Id") == "")
    }
    , Init: function() {
        if (!Core.IsInit) {
            Core.IsInit = true;
            if (Core.IsView()) {
                Core.ActionEdit();
                Core.InitProgress();
            }
        }
    }

    , InitProgress: function() {
        var divAct = document.createElement('div');
        var divBox = document.createElement('div');
        var divPro = document.createElement('div');
        var divCon = document.createElement('div');
        var divHea = document.createElement('div');
        var divBod = document.createElement('div');
        //
        divAct.id = "divActividad";
        divAct.className = "activity_overlay";
        divAct.style.display = "none";
        //
        divBox.className = "activity_box";
        divPro.className = "activity_progress";
        divCon.className = "activity_container";
        divHea.className = "activity_header";
        divBod.className = "activity_body";
        //
        divHea.innerText = Core.ProcessMessage;
        divBod.innerHTML = "<img alt='" + Core.ProcessMessage + "' src='" + Core.ProcessImage + "'/>";
        //
        divCon.appendChild(divHea);
        divCon.appendChild(divBod);

        divPro.appendChild(divCon);
        divBox.appendChild(divPro);
        divAct.appendChild(divBox);
        //
        $("body").append(divAct);
    }

    /*
    * Metodo destinado a recuperar de la URL actual el Valor del Parametro indicado
    */
    , GetUrlParam: function(ParamName) {
        var name = ParamName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null) { return ""; }
        else { return results[1]; }
    }
    , CheckLibrary: function(libType, libName) {
        if (typeof (libType) == 'undefined') {
            var sCad = "No se encuentra definida la libreria: " + (typeof (libName) == "string") ? libName : libType.toString();
            alert("Advertencia\r\n" + sCad);
            return false;
        }
        return true;
    }

    /*
    * Metodo destinado a cargar ficheros adicionales necesarios para la implementacion
    */
    , IncludeFiles: function() {
        var pathTo = "/Assets/js/"; // need to be ajusted
        var minver = false;
        var modules = [
            { include: true, incfile: 'flexigrid.js', minfile: 'min/flexigrid.min.js' },
            { include: true, incfile: 'jqModal.js', minfile: 'min/jqModal.min.js' }, // jqGrid common for editing
            {include: true, incfile: 'json2.js', minfile: 'min/json2.min.js' }
        ];
        var filename;
        for (var i = 0; i < modules.length; i++) {
            if (modules[i].include === true) {
                if (minver !== true) {
                    filename = pathTo + modules[i].incfile;
                } else {
                    filename = pathTo + modules[i].minfile;
                }
                if (jQuery.browser.safari || jQuery.browser.msie) {
                    jQuery.ajax({ url: filename, dataType: 'script', async: false, cache: false });
                } else {
                    var oHead = document.getElementsByTagName('head')[0];
                    var oScript = document.createElement('script');
                    oScript.type = 'text/javascript';
                    oScript.src = filename;
                    oHead.appendChild(oScript);
                }
            }
        }
    }
    /*
    * Metodo destinado a realizar las llamadas asinronas
    *
    * @url        : direccion url a solicitar
    * @parametros : parametro a enviar (objeto json) como string
    * @fxSucces   : funcion a ejecutar si la solicitud es exitosa
    * @fxError    : funcion a ejecutar si la solicitud presenta problemas
    */
    , RequestStart: function(url, parametros, btnCaller, fxSucces, fxError) {
        //Validar que exista la libreria
        if (!Core.CheckLibrary(JSON.stringify, "json2")) { return false; }
        //
        var sData = parametros;
        if (typeof (parametros) == 'undefined') return;
        if (typeof (parametros) != 'string') {
            sData = JSON.stringify(parametros);
        }

        $.ajax({
            type: 'POST',
            url: url,
            data: sData,
            beforeSend: function(xhr) {
                if (typeof (btnCaller) == 'object') { btnCaller.disable = true; }
                //Presentar dialogo de Actividad
                Core.ActivityStart();
                //
                xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
            },
            contentType: "application/json; charset=utf-8", //Set Content-Type
            dataType: "json", // Set return Data Type
            success: function(msg, status) {
                if (typeof (btnCaller) == 'object') { btnCaller.disable = false; }
                //Detener dialogo de Actividad
                Core.ActivityStop();
                //
                if (typeof (fxSucces) == 'function')
                    fxSucces(msg, status);
            },
            error: function(xhr, msg, e) {
                if (typeof (btnCaller) == 'object') { btnCaller.disable = false; }
                //Detener dialogo de Actividad
                Core.ActivityStop();
                //
                if (typeof (fxError) == 'function') {
                    fxError(xhr, msg, e);
                } else {
                    alert('Estado:' + xhr.status + ' , ' + xhr.statusText);
                }
            }
        });
    }

    /*
    * Metodo encargado de presentar la animacion de Actividad
    *
    * NT: Es necesario definir la siguiente seccion HTML
    *   <div id="divActividad"  style="display:none;margin-left: 10px;">
    *     <div class="activity_progress">
    *      <div class="activity_container">
    *        <div class="activity_header">Procesando ...</div>
    *        <div class="activity_body"><img src="<% Response.Write(ResolveUrl("~/Assets/images/activity.gif")); %>" /></div>
    *      </div>
    *     </div> 
    *   </div>     
    */
    , ActivityStart: function() {
        if (Core.ModalActividad == null) {
            Core.ModalActividad = $(Core.IdModalActividad);
        }
        Core.ModalActividad.show();
        return true;
    }
    /*
    * Metodo encargado de detener la animacion de Actividad
    */
    , ActivityStop: function() {
        if (Core.ModalActividad != null) {
            Core.ModalActividad.hide();
        }
        return true;
    }

    , GrillaSearch: function(oEntity, btnCaller) {
        if (typeof (oEntity) != 'object') return;

        var sName = oEntity.IdentityName;
        Core.RequestStart(Core.ManttoPath + "?View=" + sName + "&Action=2"
                               , oEntity.Item
                               , btnCaller
                               , Core.GrillaSearchSucces);
    }
    , GrillaSearchSucces: function(msg, status) {
        $(Core.IdTablaDetalle).flexAddData(msg);
    }
    /*
    * Metodo encargado de configurar la Grilla Indicada
    */
    , GrillaConfig: function(oEntity) {
        if (typeof (oEntity.IdentityName) != 'string' || !Core.IsView()) return;
        //Validar que exista la libreria
        if (!Core.CheckLibrary(jQuery.fn.flexigrid, "FlexiGrid")) { return false; }
        //
        if (!Core.IsInit) { Core.Init(); }
        //
        var sName = oEntity.IdentityName;
        var width = $(Core.IdGridView).parent().width() - 17;
        var oCol = oEntity.Columns;
        //
        $(Core.IdGridView).flexigrid({
            url: Core.ManttoPath + "?View=" + oEntity.IdentityName
            , dataType: "json"
            , colModel: oCol
            , sortname: "Id"
            , sortorder: "asc"
            , usepager: true
            , title: oEntity.IdentityName
            , useRp: true
            , rp: 10
            , showTableToggleBtn: false
            , showToggleBtn: false
            , width: width
            , height: 200
            , singleSelect: true
            , resizable: false
            , pagestat: "Registros, {from} a {to} de un total de {total}"
            , striped: false
            //Despues de Obtener los datos y antes de procesarlos
            //Parsear los datos recuperados de acuerdo a lo esperado x la grilla
            , preProcess: function(data) {
                var oRows = data.Rows;
                var oArr = new Array(oRows.length);

                //Modelo de Columnas utilizadas
                //Para cada una de la columnas, analizar sus relaciones y reemplazar el Id x Descripcion
                for (i = 0; i < oCol.length; i++) {
                    if (oCol[i].relation != null) {
                        //Buscar el DropDownList con la informacion
                        var cbo = $(':input[id$="ctl' + oCol[i].name + '"]');
                        if (cbo.length > 0) {
                            for (x = 0; x < oRows.length; x++) {
                                for (idx = 0; idx < cbo[0].options.length; idx++) {
                                    if (oRows[x][oCol[i].name] == cbo[0].options[idx].value) {
                                        oRows[x][oCol[i].name] = cbo[0].options[idx].text;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                //Parsear la informacion de acuerdo al modelo de datos procesable
                for (x = 0; x < oRows.length; x++) {
                    var oVal = new Array();
                    //Modelo de Columnas utilizadas
                    for (i = 0; i < oCol.length; i++) {
                        oVal[i] = oRows[x][oCol[i].name];
                        if (oCol[i].name == 'Id') {
                            oVal[i] = '<a href="' + Core.ManttoPath + '?View=' + oEntity.IdentityName + '&Id=' + oVal[i] + '&TB_iframe=true" class="jqBox" title="Editar informaci&oacute;n ..." >Editar</a>';
                        }
                    }
                    oArr[x] = {
                        id: oRows[x]['Id']
                        , cell: oVal
                    };
                }
                //
                data.Rows = oArr;
                return data;
            }
            , onSuccess: function() {
                Core.ActivityStop();
                Core.ActionEdit();
            }
            , onError: Core.ActivityStop
            //Antes de solicitar la informacion
            , onSubmit: Core.ActivityStart
        });

    }

    /*
    * Metodo encargado de Capturar los Eventos de los Botones de la Grilla
    */
    , GrillaActionButton: function(com, grid) {

        if (com == 'Delete') {
            var Id = 0;
            var row = $('.trSelected', grid);
            if (row.length > 0) {
                Id = parseInt(row[0].id.replace('row', ''));
                if (confirm('¿ Realmente desea eliminar la informaci&oacute;n seleccionada ? ') == true) {
                    $('#' + Core.IdTablaDetalle).flexReload();
                    //$('#' + Core.IdTablaDetalle).flexOptions({ newp: 1 }).flexReload();
                }
            }
        }
        else if (com == 'Add') {
            alert('Add New Item');
        }
    }
    /*
    * Metodo destinado a configurar para cada fila el PopUpDialog 
    */
    , ActionEdit: function() {
        $("a.jqBox").unbind("click");
        $("a.jqBox").click(function() {
            var t = this.title || this.name || null;
            var a = this.href || this.alt;
            var g = this.rel || false;

            jqBox.tb_show(t, a, g);
            this.blur();

            return false;
        });
    }
    , ActionEditClose: function(message) {

        try {
            top.jqBox.tb_remove();
            if (typeof (message) == "string") {
                top.$('[id$="lblMessage"]').html(message);
            }
            top.$(Core.IdGridView).flexReload();
        } catch (ex) { }

        //        jqBox.tb_remove();
        //        $(Core.IdGridView).flexReload();
    }
};

var jqBox = {

    loadStart: Core.ActivityStart
    , loadStop: Core.ActivityStop
    , tb_show: function(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
        try {
            if (typeof (document.body.style.maxHeight) == "undefined") {//if IE 6
                $("body", "html").css({ height: "100%", width: "100%" });
                $("html").css("overflow", "hidden");
                if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
                    $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
                }
            } else {//all others
                if (document.getElementById("TB_overlay") === null) {
                    $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
                }
            }

            if (jqBox.tb_detectMacXFF()) {
                $("#TB_overlay").addClass("TB_overlayMacFFBGHack"); //use png overlay so hide flash
            } else {
                $("#TB_overlay").addClass("TB_overlayBG"); //use background and opacity
            }

            if (caption === null) { caption = ""; }
            //$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
            jqBox.loadStart(); //$('#TB_load').show();//show loader

            var baseURL;
            if (url.indexOf("?") !== -1) { //ff there is a query string involved
                baseURL = url.substr(0, url.indexOf("?"));
            } else {
                baseURL = url;
            }

            var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
            var urlType = baseURL.toLowerCase().match(urlString);

            var queryString = url.replace(/^[^\?]+\??/, '');
            var params = jqBox.tb_parseQuery(queryString);

            TB_WIDTH = (params['width'] * 1) + 30 || 650; //defaults to 630 if no paramaters were added to URL
            TB_HEIGHT = (params['height'] * 1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
            ajaxContentW = TB_WIDTH - 30;
            ajaxContentH = TB_HEIGHT - 45;

            if (url.indexOf('TB_iframe') != -1) {// either iframe or ajax window		
                urlNoQuery = url.split('TB_');
                $("#TB_iframeContent").remove();
                if (params['modal'] != "true") {//iframe no modal
                    $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Cerrar'>Cerrar</a></div></div><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='jqBox.tb_showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;' > </iframe>");
                } else {//iframe modal
                    $("#TB_overlay").unbind();
                    $("#TB_window").append("<iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='jqBox.tb_showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;'> </iframe>");
                }
            }

            $("#TB_closeWindowButton").click(jqBox.tb_remove);

            if (url.indexOf('TB_iframe') != -1) {
                jqBox.tb_position();
                if ($.browser.safari) {//safari needs help because it will not fire iframe onload
                    //$("#TB_load").remove();
                    $("#TB_window").css({ display: "block" });
                }
            }

            if (!params['modal']) {
                document.onkeyup = function(e) {
                    if (e == null) { // ie
                        keycode = event.keyCode;
                    } else { // mozilla
                        keycode = e.which;
                    }
                    if (keycode == 27) { // close
                        jqBox.tb_remove();
                    }
                };
            }

        } catch (e) {
            //nothing here
        }
    }

    //helper functions below
    , tb_showIframe: function() {
        jqBox.loadStop(); //$("#TB_load").remove();	
        $("#TB_window").css({ display: "block" });
    }

    , tb_remove: function() {
        $("#TB_imageOff").unbind("click");
        $("#TB_closeWindowButton").unbind("click");
        $("#TB_window").fadeOut("fast", function() { $('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove(); });
        if ($("#TB_window").length > 0) jqBox.loadStop(); //$("#TB_load").remove();
        if (typeof (document.body.style.maxHeight) == "undefined") {//if IE 6
            $("body", "html").css({ height: "auto", width: "auto" });
            $("html").css("overflow", "");
        }
        document.onkeydown = "";
        document.onkeyup = "";
        return false;
    }

    , tb_position: function() {
        $("#TB_window").css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px' });
        if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
            $("#TB_window").css({ marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px' });
        }
    }

    , tb_parseQuery: function(query) {
        var Params = {};
        if (!query) { return Params; } // return empty object
        var Pairs = query.split(/[;&]/);
        for (var i = 0; i < Pairs.length; i++) {
            var KeyVal = Pairs[i].split('=');
            if (!KeyVal || KeyVal.length != 2) { continue; }
            var key = unescape(KeyVal[0]);
            var val = unescape(KeyVal[1]);
            val = val.replace(/\+/g, ' ');
            Params[key] = val;
        }
        return Params;
    }

    , tb_getPageSize: function() {
        var de = document.documentElement;
        var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
        var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
        arrayPageSize = [w, h];
        return arrayPageSize;
    }

    , tb_detectMacXFF: function() {
        var userAgent = navigator.userAgent.toLowerCase();
        if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
            return true;
        }
    }

};

$(document).ready(function() {
    Core.Init();
});